package ru.hh.school;

import ru.hh.school.util.BlockingQueue;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class UserOutput implements Runnable {
    private ObjectOutputStream stream;
    private BlockingQueue<String> messages;
    private ChatRouter router;
    private User user;

    public UserOutput(OutputStream stream, User user, ChatRouter router) throws IOException {
        messages = new BlockingQueue<String>(10000);
        this.stream = new ObjectOutputStream(stream);
        this.router = router;
        this.user = user;
    }

    public void add(String message) {
        messages.add(message);
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                stream.writeObject(messages.take());
                stream.flush();
            }
        } catch (IOException e) {
            router.command(user, "/quit Disconnected");
        } catch (InterruptedException e) {
            //ignore
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                //ignore
            }
        }

    }

}
